package cn.com.xf.web.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.ConfigUtil;
import cn.com.xf.common.Constants;
import cn.com.xf.common.PinyinUtils;
import cn.com.xf.domain.TblSiteApp;
import cn.com.xf.service.TblSiteAppService;
import cn.com.xf.web.form.BeeAppForm;

@Controller
@RequestMapping("/site")
public class BeeAppController extends AbstractBaseController {

	@Autowired
	private TblSiteAppService tblSiteAppService;
	
	@RequestMapping("/appAdd")
	public ModelAndView add(HttpServletRequest request, HttpServletResponse response, BeeAppForm form) {
		ModelAndView mv = new ModelAndView("/site/add_app", Constants.FORM_COMMAND_KEY, form);
		return mv;
	}
	
	@RequestMapping("/doAppAdd")
	public ModelAndView doAdd(HttpServletRequest request, HttpServletResponse response, @Valid BeeAppForm form, BindingResult result) {
		ModelAndView mv = new ModelAndView("/site/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		
		String tempFileId = form.getTempFileId();
		if (StringUtils.isBlank(form.getTempFileId())) {
			return null;
		}
		
		TblSiteApp app = new TblSiteApp();
		String formalFileName = "";
		String tempFilesPath = servletContext.getRealPath("/") + Constants.UPLOAD_PATH_TEMP;
		File dir = new File(tempFilesPath);
		File file[] = dir.listFiles();
		// 2.3转存到正式的目录
		for (File f : file) {
			if (f.isFile()) {
				String allname = f.getName();
				if (allname.contains(Constants.UPLOAD_TEMP_SPILT)) {
					String name = allname.split(Constants.UPLOAD_TEMP_SPILT)[0];
					if (tempFileId.equalsIgnoreCase(name)) {
						formalFileName = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + "_"
								+ PinyinUtils.converterToSpell(allname.split(Constants.UPLOAD_TEMP_SPILT)[1]);
						String absoluteFlvPath = ConfigUtil.getValue(Constants.ABSOLUTE_ROOT_NAME) + File.separator
								+ Constants.ABSOLUTE_ROOT_APK_PATH;
						File flvFile = new File(absoluteFlvPath);
						if (!flvFile.exists()) {
							flvFile.mkdirs();
						}
						File siteFormalFile = new File(absoluteFlvPath, formalFileName);
						fileChannelCopy(f, siteFormalFile);
					}
				}
			}
		}
		if (StringUtils.isBlank(formalFileName)) {
			return null;
		}
		
		app.setAppName("xfAndroidBee");
		app.setVersionCode(form.getVersionCode());
		app.setPath(formalFileName);
		tblSiteAppService.addXfAndroidBee(app);
		mv.addObject("status", "SUCCESS");
		return mv;
	}
	
	private void fileChannelCopy(File s, File t) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
